<template>
  <div class="app-container home">
    <div class="left">
      <el-tree v-if="showTree" default-expand-all :data="treeData" ref="tree" :props="defaultProps"
        @node-contextmenu="openMenu" node-key="id" @node-click="nodeclick" highlight-current
        :expand-on-click-node="false">
      </el-tree>
      <el-button v-else type="primary" @click="openDialog">添加数据</el-button>
      <div v-show="showMenu" :style="menuStyle" class="customer-menu" ref="wraper">
        <ul>
          <li>
            <el-button size="small" @click="add">添加</el-button>
          </li>
          <li>
            <el-button size="small" @click="edit">编辑</el-button>
          </li>
          <li>
            <el-button size="small" @click="deleteData">删除</el-button>
          </li>
        </ul>
      </div>
    </div>
    <div class="right">
      <div>
        <el-form :inline="true" :model="formInline" class="">
          <el-form-item label="机型" prop="aircraftType">
            <el-select v-model="formInline.aircraftType" clearable>
              <el-option v-for="(item,index) in aircraftTypes" :key="'aircraftType'+index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工况类型" prop="type">
            <el-input v-model="formInline.type" clearable placeholder="请输入" size="small"></el-input>
          </el-form-item>
          <el-form-item label="子类型" prop="subType">
            <el-input v-model="formInline.subType" clearable placeholder="请输入" size="small"></el-input>
          </el-form-item>
          <el-form-item label="轮次" prop="round">
            <el-input v-model="formInline.round" clearable placeholder="请输入" size="small"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
            <el-button type="primary" plain @click="handleReset" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn">
        <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="序号" type="index" width="50" :index="indexMethod">
        </el-table-column>
        <el-table-column prop="aircraftType" label="机型"> </el-table-column>
        <el-table-column prop="typeName" label="工况类型"> </el-table-column>
        <el-table-column prop="subTypeName" label="子类型" />
        <el-table-column prop="rounds" label="轮次" />
        <el-table-column prop="count" label="数量"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="p20 fr" v-if="total > 0" :background="true" :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize" :layout="'total, sizes, prev, pager, next, jumper'"
        :page-sizes="[10, 30, 50, 100]" :total="total" @size-change="handleSizeChange"
        @current-change="handlepageNumChange" />
      <LoadCaseStatisticsDialog :datas="loadCaseStatisticsDatas" v-if="dialogVisible" :type="type"
        @on-close="handleDialogClose" @on-sure="onSearch" :nodeData="currentNode" />
      <el-dialog title="节点维护" :visible="showDialog">
        <el-form>
          <el-form-item label="节点名称">
            <el-input v-model="dialogForm.name" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSure">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import LoadCaseStatisticsDialog from '@/components/Editor/loadCaseStatisticsDialog.vue'
  import { getLoadCaseStatisticList, deleteLoadCaseStatistic, addTreeNode, updateTreeNode, deleteTreeNode, getAllTreeNode } from "@/api/loadCaseStatistics";
  export default {
    name: "loadCaseStatistics",
    components: { LoadCaseStatisticsDialog },
    data() {
      return {
        formInline: {
          keyword: "",
          classifyId: null,
          aircraftType:"",
          type:"",
          subTypeName:"",
          rounds:""
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        aircraftTypes: [
          {
            label: 'C909',
            value: 'C909'
          },
          {
            label: 'C919',
            value: 'C919'
          },
          {
            label: 'C929',
            value: 'C929'
          }
        ],
        loading: false,
        total: 0,
        tableData: [],
        dialogVisible: false,
        loadCaseStatisticsDatas: {},
        type: 'add',
        treeData: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        showDialog: false,
        dialogForm: {
          name: "",
          id: null,
          parentNodeId: null
        },
        showTree: false,
        menuStyle: {
          left: 0,
          top: 0
        },
        showMenu: false,
        currentNode: null,
        nodeEditType: 'add'
      };
    },
    methods: {
      nodeclick(data, node, prop) {
        this.formInline.classifyId = data?.id;
        this.currentNode = data;
        this.onSearch();
      },
      processData(data) {
        const labelData = data.map((el) => {
          if (el.children) {
            el = { ...el, label: el.name }
            el.children = this.processData(el.children);
          } else {
            el = { ...el, label: el.name }
          }
          return el;
        })
        return labelData;
      },
      getTree() {
        getAllTreeNode().then(async (res) => {
          if (res) {
            const resultData = res?.data || [];
            console.log(resultData)
            // console.log(resultData.length)
            if (resultData.length > 0) {
              this.showTree = true;
              this.treeData = await this.processData(resultData);
              console.log(this.treeData)
            }
          }
        })
      },
      handleSure() {
        // 第一个节点
        if (this.treeData.length == 0) {
          this.dialogForm.id = 0;
        } else {

        }
        const params = {
          id: this.nodeEditType == 'add' ? null : this.dialogForm.id,
          name: this.dialogForm.name,
          orderNum: 0,
          parentId: this.nodeEditType == 'add' ? this.currentNode.id : this.currentNode.parentId
          // parentId: 42
        }
        if (this.nodeEditType == 'add') {
          addTreeNode(params).then(res => {
            if (res) {
              this.getTree();
              this.showDialog = false;
            }
          })
        }
        if (this.nodeEditType == 'edit') {
          updateTreeNode(params).then(res => {
            if (res) {
              this.getTree();
              this.showDialog = false;
            }
          })
        }
      },
      handleClose() {
        this.showDialog = false;
      },
      openDialog() {
        this.showDialog = true;
      },
      openMenu(event, data, node) {
        this.currentNode = data;
        this.showMenu = true;
        event.preventDefault();
        this.menuStyle.left = 210 + 'px';
        this.menuStyle.top = event.clientY - 82 + 'px';
      },
      add() {
        this.nodeEditType = 'add';
        this.dialogForm.id = null;
        this.dialogForm.name = "";
        this.dialogForm.parentId = this.currentNode.id;
        this.showDialog = true;
        this.showMenu = false;
      },
      edit() {
        this.nodeEditType = 'edit';
        this.showDialog = true;
        this.dialogForm.id = this.currentNode.id;
        this.dialogForm.name = this.currentNode.name;
        this.dialogForm.parentId = this.currentNode.parentId;
        this.showMenu = false;
      },
      deleteData() {
        this.nodeEditType = 'delete';
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteTreeNode(this.currentNode.id).then(res => {
            this.$message({ type: 'success', message: '删除成功!' });
            this.getTree();
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除' });
        });
      },
      indexMethod(index) {
        return (
          (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
        );
      },
      async onSearch() {
        try {
          this.loading = true;
          const res = await getLoadCaseStatisticList({
            ...this.queryParams,
            ...this.formInline,
          });
          this.tableData = res.data.list;
          this.total = res.data.count;
        } catch (error) {
          console.log(error);
        } finally {
          this.loading = false;
        }
      },
      handleReset() {
        this.formInline = {
          keyword: "",
          classifyId: null
        };
        this.onSearch();
      },
      handleSearch() {
        this.queryParams.pageNum = 1;
        this.onSearch();
      },
      handleSizeChange(val) {
        if (this.queryParams.pageSize * val > this.total) {
          this.queryParams.pageNum = 1;
        }
        this.onSearch();
      },
      handlepageNumChange() {
        this.onSearch();
      },
      handleAdd() {
        if (!this.currentNode) {
          this.$message({ type: 'error', message: '请选择左侧树节点' });
          return;
        }
        this.loadCaseStatisticsDatas = {
          id: undefined,
          typeName: '',
          subTypeName: '',
          count: '',
          aircraftType: '',
          rounds: ''
        }
        this.type = 'add'
        this.dialogVisible = true
      },
      handleView(row) {
        this.loadCaseStatisticsDatas = row
        this.type = 'view'
        this.dialogVisible = true
      },
      handleEdit(row) {
        this.loadCaseStatisticsDatas = row
        this.type = 'edit'
        this.dialogVisible = true
      },
      handleDelete(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteLoadCaseStatistic(id).then(res => {
            this.$message({ type: 'success', message: '删除成功!' });
            this.handleSearch();
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除' });
        });
      },
      handleDialogClose() {
        this.dialogVisible = false
      },
      handleClick(event) {
        if (this.$refs.wraper && !this.$refs.wraper.contains(event.target)) {
          this.showMenu = false;
        }
      }
    },
    mounted() {
      this.handleSearch();
      this.getTree();
      window.addEventListener('click', this.handleClick)
    },
  };
</script>
<style lang="scss" scoped>
  .btn {
    padding: 16px;
  }

  .home {
    display: flex;

    .left {
      width: 20%;

      .customer-menu {
        position: absolute;
        background-color: #fff;
        border: 1px solid #ebebeb;
        border-radius: 3px;
        width: 80px;
        z-index: 1000;
        font-size: 12px;

        ul {
          margin: 0;
          padding: 5px 0;
          list-style: none;
        }

        ul li {
          padding: 3px 15px;
          cursor: pointer;
          display: flex;
          align-items: center;
        }

        ul li:hover {
          background-color: #eee;
        }
      }
    }

    .right {
      width: 80%;
    }
  }
</style>